package com.cyj.springbootservice.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyj.springbootservice.api.entity.SysDept;
import com.cyj.springbootservice.api.entity.SysDeptRelation;
import com.cyj.springbootservice.mapper.SysDeptRelationMapper;
import com.cyj.springbootservice.service.SysDeptRelationService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @Author C_Y_J
 * @create 2022/5/10 10:42
 **/
@Service
@AllArgsConstructor
public class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelation> implements SysDeptRelationService {

    private final SysDeptRelationMapper sysDeptRelationMapper;

    /**
     * 维护部门关系
     *
     * @param sysDept 部门
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertDeptRelation(SysDept sysDept) {

        // 增加部门关系表
        Integer deptId = sysDept.getDeptId();

        List<SysDeptRelation> relationList = sysDeptRelationMapper.selectList(
                Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getDescendant, sysDept.getParentId()))
                .stream().map(relation -> {
                    relation.setDescendant(deptId);
                    return relation;
                }).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(relationList)) {
            this.saveBatch(relationList);
        }

        // 自己也要维护到关系表中
        SysDeptRelation own = new SysDeptRelation();
        own.setDescendant(deptId);
        own.setAncestor(deptId);
        sysDeptRelationMapper.insert(own);
    }

    /**
     * 通过ID删除部门关系
     *
     * @param id
     */
    @Override
    public void deleteAllDeptRealtion(Integer id) {

        // baseMapper.deleteDeptRelationsById(id);

        List<Integer> relationList = sysDeptRelationMapper.selectList(
                Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, id))
                .stream().map(SysDeptRelation::getDescendant).collect(Collectors.toList());
        sysDeptRelationMapper.delete(
                Wrappers.<SysDeptRelation>query().lambda().in(SysDeptRelation::getDescendant, relationList)
        );
    }

    /**
     * 更新部门关系
     *
     * @param relation
     */
    @Override
    public void updateDeptRealtion(SysDeptRelation relation) {
         baseMapper.updateDeptRelations(relation);
    }

}

